package com.audaque.springboot.foshanupload.security.handler;

import com.audaque.springboot.foshanupload.jwt.component.JwtTokenProvider;
import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.jwtcore.component.iface.JwtProviderIface;
import com.audaque.springboot.foshanupload.jwtcore.properties.JwtProperties;
import com.audaque.springboot.foshanupload.security.util.SecurityContextAuthentication2TransmittableThreadLocalCurrentUserUtil;
import com.audaque.springboot.foshanupload.core.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zgb
 * @desc 认证成功处理器
 * @date 2022-08-05 18:00:12
 */
@Slf4j
@Component
public class MyUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JwtProviderIface jwtProviderIface;
    @Autowired
    private JwtProperties jwtProperties;

    private String getUserIdByUsername(String username) {
        return AuthConst.USER_ID;
    }


    @Autowired
    private JwtTokenProvider jwtTokenProvider;


    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String method = request.getMethod();//GET还是POST
        log.debug("method：" + method);

        String url = request.getRequestURL().toString();
        log.debug("url：" + url);

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //处理session部分
        SecurityContextAuthentication2TransmittableThreadLocalCurrentUserUtil.covert();
        //处理jwt部分
        jwtTokenProvider.sendToken(request, response);
        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();

        R r = R.ok();
        r.setData(transmittableThreadLocalCurrentUser);


        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }
}
